import { defineStore } from 'pinia';

export const useTabsStore = defineStore('useTabs', {
  state: () => ({
    tabs: [
      { title: '首页', path: '/', closable: false }, // 默认首页标签
    ],
    activeTabPath: '/',
  }),
  actions: {
    addTab(tab) {
      try {
        // 检查标签是否已存在
        const existingTab = this.tabs.find((t) => t.path === tab.path);
        if (!existingTab) {
          this.tabs.push(tab);
        }
      } catch (error) {
        console.error('添加标签页失败:', error);
        // 确保状态一致性
        if (!Array.isArray(this.tabs)) {
          this.resetState();
        }
      }
    },
    removeTab(path) {
      try {
        const index = this.tabs.findIndex((tab) => tab.path === path);
        if (index !== -1) {
          this.tabs.splice(index, 1);
        }
      } catch (error) {
        console.error('删除标签页失败:', error);
        this.resetState();
      }
    },
    setActiveTab(path) {
      try {
        this.activeTabPath = path;
      } catch (error) {
        console.error('设置激活标签页失败:', error);
        this.activeTabPath = '/';
      }
    },
    clearTabs() {
      try {
        // 保留首页，清除其他标签
        this.resetState();
      } catch (error) {
        console.error('清除标签页失败:', error);
        this.resetState();
      }
    },
    resetState() {
      // 重置为初始状态
      this.tabs = [{ title: '首页', path: '/', closable: false }];
      this.activeTabPath = '/';
    },
    // 初始化时检查状态是否有效
    initStore() {
      try {
        // 检查tabs是否是数组
        if (!Array.isArray(this.tabs) || this.tabs.length === 0) {
          this.resetState();
          return;
        }

        // 检查是否至少有首页标签
        const hasHomePage = this.tabs.some((tab) => tab.path === '/');
        if (!hasHomePage) {
          this.tabs.unshift({ title: '首页', path: '/', closable: false });
        }

        // 确保activeTabPath有效
        if (!this.activeTabPath || typeof this.activeTabPath !== 'string') {
          this.activeTabPath = '/';
        }
      } catch (error) {
        console.error('初始化标签页状态失败:', error);
        this.resetState();
      }
    },
  },
  persist: true, // 启用持久化
});
